<template>
    <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片区域 -->
      <el-card>
          <!-- 警告区域 -->
        <el-alert
        title="只允许为第三级分类选择"
        type="warning" :closable="false" show-icon >
        </el-alert>
        <el-row class="cateType">
          <el-col>
             <!-- 选择分类 -->
             <span>选择商品分类:</span>
              <!-- 级联选择框区域 -->
                <el-cascader
                 expand-trigger= "hover"
                 v-model="selectedCateKeys"
                 :options="cateList"
                 :props="cateProps"
                 @change="handleChange" class="cascaderCate"></el-cascader>
          </el-col>
        </el-row>
        <!-- Tab 页签区域 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 添加动态参数面板 -->
            <el-tab-pane label="用户管理" name="many">
                <!-- 添加参数按钮 -->
                <el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="addDialogVisible=true">添加参数</el-button>
                <!-- 动态参数表格 -->
            <el-table :data="manyTableDate" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope" >
                            <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleClose(i,scope.row)">{{item}}</el-tag>
                          <!-- 添加标签 -->
                            <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            
                    </template>
                </el-table-column>
                <el-table-column type="index" prop=""></el-table-column>
                <el-table-column label="添加数据" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                    <template  slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDiologForm(scope.row.attr_id)">修改</el-button> 
                        <el-button size="mini" type="danger"  icon="el-icon-delete" @click="removeConfimResult(scope.row.attr_id)" >删除</el-button> 

                       
                         
                    </template>
                </el-table-column>
            </el-table>
            </el-tab-pane>
            
            <!-- 添加静态属性的面板 -->
            <el-tab-pane label="配置管理" name="only">
                <!-- 添加属性的按钮 -->
                <el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="addDialogVisible=true">添加属性</el-button>
                <!-- 静态表格 -->
            <el-table :data="onlyTableDate" border stripe>
                <!-- 下拉按钮 -->
                 <el-table-column type="expand">
                       <template slot-scope="scope" >
                            <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleClose(i,scope.row)">{{item}}</el-tag>
                          <!-- 添加标签 -->
                            <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            
                    </template>
                 </el-table-column>
                 <!-- 索隐列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="添加数据" prop="attr_name"></el-table-column>
                <el-table-column label="操作">
                  
                    <template slot-scope="scope">
                        <el-button  size="mini" type="primary" icon="el-icon-edit" @click="showEditDiologForm(scope.row.attr_id)">编辑</el-button> 
                        <el-button  size="mini" type="danger"  icon="el-icon-delete" 
                        @click="removeConfimResult(scope.row.attr_id)">删除</el-button> 
                         
                    </template>
                </el-table-column>
            </el-table>
            </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 添加动态属性静态按钮对话框 -->
      <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addDialogVisible"
        width="50%" @close="addDialogVisibleClose">
        <!-- 参数表单验证 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
        </el-dialog>

         <!-- 修改动态属性静态按钮对话框 -->
      <el-dialog
        :title="'修改'+titleText"
        :visible.sync="editDialogVisible"
        width="50%" @close="editDialogVisibleClose">
        <!-- 参数表单验证 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
        </el-dialog>
      
    </div>
</template>
<script>
import { async } from 'q'
export default {
    data(){
        return {
            // 配置数据
            cateList:[],
            // 级联选者框配置数据
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            // 级联选择框双向绑定数据
            selectedCateKeys:[],
            activeName:'many',
            manyTableDate:[],
            onlyTableDate:[],
            addDialogVisible:false,
            // 添加数据的表单
            addForm:{
                 attr_name:''
            },
            // 添加数据表单的验证规则
            addFormRules:{
                    attr_name:[{required:true,message:'请输入参数名称',trigger:'blur'}]
            },
            editForm:{
                  
            },
             editFormRules:{
                    attr_name:[{required:true,message:'请输入参数名称',trigger:'blur'}]
            },
            editDialogVisible:false,
            




        }
       
    },
    created(){
        this.getCateList()
    },
    methods:{
         async getCateList(){
           const {data:res} = await this.$http.get('categories')
            if (res.meta.status!==200){
                return this.$message.error('获取数据列表失败!')
            }
            this.cateList=res.data
            console.log( this.cateList);
            
        },
        // 分类列表级联选择器选中会触发这个事件
        async handleChange(){
            this.getParamsData()
        },
        handleTabClick(){
            console.log(this.activeName);
            this.getParamsData()
            
        },
        // 获取参数列表
        async getParamsData(){
              // 证明选中的是三级分类
            if(this.selectedCateKeys.length!==3){
                this.selectedCateKeys=[]
                this.manyTableDate= []
                this.onlyTableDate= []
                return
            }
            // 证明选中的不是三级分类
            
            console.log(this.selectedCateKeys);
            // 根据所选分类的id 和当前所处的面板获取对应的参数
             const {data:res}= await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
            if (res.meta.status!==200){
                return this.$message.error('获取数据列表失败')
            }
            
            res.data.forEach(item => {
                item.attr_vals= item.attr_vals ? item.attr_vals.split(' '): []
                // 控制  标签的显示与隐藏
                item.inputVisible=false,
                item.inputValue=''
                
            });
            console.log(res.data);
            
            if (this.activeName==='many'){
                this.manyTableDate=res.data
            }else{
                 this.onlyTableDate=res.data
            }
        },
        addDialogVisibleClose(){
            this.$refs.addFormRef.resetFields()
        },
        // 点击按钮，添加参数
        // _____________________________________________
        // 这段太难了
        addParams(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid)return
                const {data:res}= await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!==201){
                    return this.$message.error('添加数据失败')
                }
                this.$message.success('添加数据成功')
                this.getParamsData()
                this.addDialogVisible=false
            })
        },
        // ____________________________________________
        // 点击按钮，展示修改的对话框
        async showEditDiologForm(attr_id){
            //  获取当前数据
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{
                params:{attr_sel:this.activeName}
            })
            if(res.meta.status!==200){
                return this.$message.error('获取参数失败')
            }
            this.editForm=res.data
            this.editDialogVisible=true
        },
        // 点击按钮修改参信息
         editParams(){
           this.$refs.editFormRef.validate( async valid=>{
               if (!valid)return
               const {data:res}= await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                   attr_name:this.editForm.attr_name,attr_sel:this.activeName
               })
               if (res.meta.status !==200){
                   return this.$message.error('修改数据失败')
               }
               this.$message.success('更新数据成功')
               this.getParamsData()
               this.editDialogVisible=false
           })
        },
        editDialogVisibleClose(){
            this.$refs.editFormRef.resetFields()
        },
    async removeConfimResult(attr_id){
          const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        // 取消删除用户操作
        if (confirmResult!=='confirm'){
            return this.$message.info('删除用户取消!')
        }
        // 确认了删除用户
        const {data:res}= await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        if(res.meta.status!==200){
            return this.$message.error('删除失败!')
        }
        this.$message.success('删除参数成功!')
        this.getParamsData()
        
        
        },
        // 标签输入框 按下鼠标和键盘都会触发
        async handleInputConfirm(row){
            if(row.inputValue.trim().length=== 0){
                row.inputValue=''
                row.inputVisible=false
                return
            }
            //输入框有内容后续操作
            row.attr_vals.push(row.inputValue.trim())
             row.inputValue=''
             row.inputVisible=false
             //向服务器请求添加标签数据
             this.saveAttrTrals(row)
            
        },
        // 标签展示框
        showInput(row){
            row.inputVisible=true
            // 让文本框自动获得焦点
            //nextTick方法  当页面从新被渲染的时候菜户已指定回调函数的代码
            this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
        },
        async saveAttrTrals(row){
                //向服务器请求添加标签数据
             const{data:res}= await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                 attr_name:row.attr_name,
                 attr_sel:row.attr_sel,
                 attr_vals:row.attr_vals.join(' ')
             })
             if(res.meta.status!==200){
                 return this.$message.error('修改参数数据失败!')
             }
             this.$message.success('修改参数成功!')
        },
        // 删除标签事件
        handleClose(i,row){
            row.attr_vals.splice(i,1)
            this.saveAttrTrals(row)
        }


    },
    computed:{
    isBtnDisabled(){
        if(this.selectedCateKeys.length!==3){
            return true
        }
        return false
    },
    cateId(){
        if(this.selectedCateKeys.length===3){
            return this.selectedCateKeys[2]
        }
        return null
    },
    titleText(){
        if(this.activeName=='many'){
            return '动态参数'
        }
        return '静态数据'
    }
  }
}
</script>

<style lang="less" scoped>
.cateType {
    margin-top: 15px;
}
.cascaderCate {
    margin-left: 10px;
}
.el-tag {
    margin: 10px;
}
.el-input {
    width: 100px;
}

</style>style